import React, { useState, useEffect } from 'react';
import { Table, Input, Select, Button, Space, Tooltip, Tag, Empty, message } from 'antd';
import { SearchOutlined, ClearOutlined, EyeOutlined } from '@ant-design/icons';
import { 
    DubboConsumerDTO, 
    getDubboConsumers, 
    MatchStatus 
} from '../../../../services/dubboAnalysis';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import type { SorterResult, FilterValue } from 'antd/es/table/interface';

const { Option } = Select;

interface DubboConsumerTableProps {
    unitId: string;
    onViewProviderDetail: (consumer: DubboConsumerDTO) => void;
}

const DubboConsumerTable: React.FC<DubboConsumerTableProps> = ({ unitId, onViewProviderDetail }) => {
    const [loading, setLoading] = useState<boolean>(false);
    const [consumers, setConsumers] = useState<DubboConsumerDTO[]>([]);
    const [filteredConsumers, setFilteredConsumers] = useState<DubboConsumerDTO[]>([]);
    
    // 筛选条件
    const [searchKeyword, setSearchKeyword] = useState<string>('');
    const [selectedMatchStatus, setSelectedMatchStatus] = useState<MatchStatus | undefined>(undefined);
    
    // 排序状态
    const [sortField, setSortField] = useState<string | undefined>(undefined);
    const [sortOrder, setSortOrder] = useState<'ascend' | 'descend' | undefined>(undefined);

    // 匹配状态配置
    const matchStatusConfig = {
        [MatchStatus.MATCHED]: { 
            label: '已匹配', 
            color: 'green',
            order: 1
        },
        [MatchStatus.VERSION_MISMATCH]: { 
            label: '版本不匹配', 
            color: 'orange',
            order: 2
        },
        [MatchStatus.NOT_FOUND]: { 
            label: '未找到', 
            color: 'red',
            order: 3
        }
    };

    // 加载 Consumer 数据
    const loadConsumers = async () => {
        setLoading(true);
        try {
            const data = await getDubboConsumers(unitId);
            setConsumers(data);
            applyFilters(data, searchKeyword, selectedMatchStatus);
        } catch (error: any) {
            message.error(error.message || '加载 Consumer 列表失败');
            setConsumers([]);
            setFilteredConsumers([]);
        } finally {
            setLoading(false);
        }
    };

    // 应用筛选条件
    const applyFilters = (
        data: DubboConsumerDTO[],
        keyword: string,
        matchStatus: MatchStatus | undefined
    ) => {
        let filtered = [...data];

        // 按接口名称搜索（模糊匹配）
        if (keyword.trim()) {
            const lowerKeyword = keyword.toLowerCase();
            filtered = filtered.filter(c =>
                c.interfaceFqn.toLowerCase().includes(lowerKeyword) ||
                c.interfaceSimpleName.toLowerCase().includes(lowerKeyword)
            );
        }

        // 按匹配状态筛选
        if (matchStatus) {
            filtered = filtered.filter(c => c.matchStatus === matchStatus);
        }

        setFilteredConsumers(filtered);
    };

    // 处理搜索
    const handleSearch = (value: string) => {
        setSearchKeyword(value);
        applyFilters(consumers, value, selectedMatchStatus);
    };

    // 处理匹配状态筛选
    const handleMatchStatusChange = (value: MatchStatus | undefined) => {
        setSelectedMatchStatus(value);
        applyFilters(consumers, searchKeyword, value);
    };

    // 重置所有筛选条件
    const handleReset = () => {
        setSearchKeyword('');
        setSelectedMatchStatus(undefined);
        setSortField(undefined);
        setSortOrder(undefined);
        setFilteredConsumers(consumers);
    };

    // 处理表格变化（排序）
    const handleTableChange = (
        pagination: TablePaginationConfig,
        filters: Record<string, FilterValue | null>,
        sorter: SorterResult<DubboConsumerDTO> | SorterResult<DubboConsumerDTO>[]
    ) => {
        if (!Array.isArray(sorter)) {
            setSortField(sorter.field as string);
            setSortOrder(sorter.order === null ? undefined : sorter.order);
        }
    };

    // 初始加载
    useEffect(() => {
        loadConsumers();
    }, [unitId]);

    // 表格列定义
    const columns: ColumnsType<DubboConsumerDTO> = [
        {
            title: '接口名称',
            dataIndex: 'interfaceSimpleName',
            key: 'interfaceSimpleName',
            width: 200,
            fixed: 'left',
            sorter: (a, b) => a.interfaceFqn.localeCompare(b.interfaceFqn),
            sortOrder: sortField === 'interfaceSimpleName' ? sortOrder : undefined,
            render: (text: string, record: DubboConsumerDTO) => (
                <Tooltip title={record.interfaceFqn} placement="topLeft">
                    <span style={{ 
                        fontWeight: 500, 
                        color: '#1890ff',
                        cursor: 'pointer'
                    }}>
                        {text}
                    </span>
                </Tooltip>
            ),
        },
        {
            title: '服务分组',
            dataIndex: 'serviceGroup',
            key: 'serviceGroup',
            width: 120,
            render: (text: string) => text || <span style={{ color: '#999' }}>-</span>,
        },
        {
            title: '版本号',
            dataIndex: 'version',
            key: 'version',
            width: 100,
            render: (text: string) => text || <span style={{ color: '#999' }}>-</span>,
        },
        {
            title: '匹配状态',
            dataIndex: 'matchStatus',
            key: 'matchStatus',
            width: 120,
            align: 'center',
            sorter: (a, b) => {
                const orderA = matchStatusConfig[a.matchStatus].order;
                const orderB = matchStatusConfig[b.matchStatus].order;
                return orderA - orderB;
            },
            sortOrder: sortField === 'matchStatus' ? sortOrder : undefined,
            render: (status: MatchStatus) => {
                const config = matchStatusConfig[status];
                return (
                    <Tag color={config.color} style={{ fontWeight: 500 }}>
                        {config.label}
                    </Tag>
                );
            },
        },
        {
            title: '提供者单元',
            key: 'providerUnit',
            width: 150,
            render: (_, record: DubboConsumerDTO) => {
                // Provider 信息暂时不包含 unitName，显示占位符
                // TODO: 后端需要在 DubboProviderDTO 中添加 unitId/unitName 字段
                if (record.provider && record.matchStatus === MatchStatus.MATCHED) {
                    return (
                        <span style={{ color: '#999' }}>
                            待完善
                        </span>
                    );
                }
                return <span style={{ color: '#999' }}>-</span>;
            },
        },
        {
            title: '提供者应用',
            key: 'providerApp',
            width: 150,
            render: (_, record: DubboConsumerDTO) => {
                // Provider 信息暂时不包含 appName，显示占位符
                // TODO: 后端需要在 DubboProviderDTO 中添加 appId/appName 字段
                if (record.provider && record.matchStatus === MatchStatus.MATCHED) {
                    return (
                        <span style={{ color: '#999' }}>
                            待完善
                        </span>
                    );
                }
                return <span style={{ color: '#999' }}>-</span>;
            },
        },
        {
            title: '超时配置',
            dataIndex: 'timeout',
            key: 'timeout',
            width: 100,
            align: 'center',
            render: (text: string) => text || <span style={{ color: '#999' }}>-</span>,
        },
        {
            title: '配置文件',
            dataIndex: 'filePath',
            key: 'filePath',
            width: 250,
            ellipsis: {
                showTitle: false,
            },
            render: (text: string) => (
                <Tooltip title={text} placement="topLeft">
                    <span style={{ color: '#666', fontSize: '12px' }}>{text}</span>
                </Tooltip>
            ),
        },
        {
            title: '行号',
            dataIndex: 'lineNumber',
            key: 'lineNumber',
            width: 80,
            align: 'center',
            render: (text: number) => text || <span style={{ color: '#999' }}>-</span>,
        },
        {
            title: '操作',
            key: 'action',
            width: 120,
            fixed: 'right',
            align: 'center',
            render: (_, record: DubboConsumerDTO) => (
                <Button
                    type="link"
                    size="small"
                    icon={<EyeOutlined />}
                    onClick={() => onViewProviderDetail(record)}
                >
                    查看详情
                </Button>
            ),
        },
    ];

    return (
        <div style={{ marginBottom: '24px' }}>
            {/* 标题 */}
            <div style={{
                fontSize: '18px',
                fontWeight: '600',
                color: '#333',
                marginBottom: '16px',
                display: 'flex',
                alignItems: 'center'
            }}>
                <span style={{ 
                    display: 'inline-block',
                    width: '4px',
                    height: '18px',
                    background: '#1890ff',
                    marginRight: '8px',
                    borderRadius: '2px'
                }} />
                消费的服务列表
            </div>

            {/* 筛选栏 */}
            <div style={{
                background: '#fff',
                padding: '16px',
                borderRadius: '8px',
                marginBottom: '16px',
                boxShadow: '0 2px 8px rgba(0,0,0,0.06)'
            }}>
                <Space size="middle" wrap>
                    {/* 搜索框 */}
                    <Input
                        placeholder="按接口名称搜索..."
                        prefix={<SearchOutlined style={{ color: '#bfbfbf' }} />}
                        value={searchKeyword}
                        onChange={(e) => handleSearch(e.target.value)}
                        onPressEnter={() => handleSearch(searchKeyword)}
                        allowClear
                        style={{ width: 280 }}
                    />

                    {/* 匹配状态筛选 */}
                    <Select
                        placeholder="选择匹配状态"
                        value={selectedMatchStatus}
                        onChange={handleMatchStatusChange}
                        allowClear
                        style={{ width: 180 }}
                    >
                        {Object.entries(matchStatusConfig).map(([status, config]) => (
                            <Option key={status} value={status}>
                                <Tag color={config.color} style={{ marginRight: 8 }}>
                                    {config.label}
                                </Tag>
                            </Option>
                        ))}
                    </Select>

                    {/* 重置按钮 */}
                    <Button
                        icon={<ClearOutlined />}
                        onClick={handleReset}
                    >
                        重置
                    </Button>
                </Space>

                {/* 筛选结果提示 */}
                {(searchKeyword || selectedMatchStatus) && (
                    <div style={{ 
                        marginTop: '12px', 
                        fontSize: '13px', 
                        color: '#666' 
                    }}>
                        已筛选 <span style={{ color: '#1890ff', fontWeight: 500 }}>{filteredConsumers.length}</span> 条结果
                        {searchKeyword && ` · 关键词: "${searchKeyword}"`}
                        {selectedMatchStatus && ` · 状态: ${matchStatusConfig[selectedMatchStatus].label}`}
                    </div>
                )}
            </div>

            {/* 表格 */}
            <Table
                columns={columns}
                dataSource={filteredConsumers}
                rowKey="configId"
                loading={loading}
                onChange={handleTableChange}
                pagination={{
                    pageSize: 20,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total) => `共 ${total} 条`,
                    pageSizeOptions: ['10', '20', '50', '100'],
                }}
                scroll={{ x: 1600 }}
                locale={{
                    emptyText: (
                        <Empty
                            description={
                                <span style={{ color: '#999' }}>
                                    {searchKeyword || selectedMatchStatus
                                        ? '没有找到匹配的服务'
                                        : '暂无消费的服务'}
                                </span>
                            }
                        />
                    ),
                }}
                style={{
                    background: '#fff',
                    borderRadius: '8px',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.06)'
                }}
            />
        </div>
    );
};

export default DubboConsumerTable;
